﻿using System.Web.Mvc;

namespace CodeContrib.Web.Mvc.Html
{
	public static class AlertExtensions
	{
		public static MvcHtmlString Alert(this HtmlHelper htmlHelper, MvcHtmlString innerHtml, AlertType alertType)
		{
			return Alert(htmlHelper, (innerHtml == null) ? null : innerHtml.ToHtmlString(), null, alertType);
		}

		public static MvcHtmlString Alert(this HtmlHelper htmlHelper, string innerHtml, AlertType alertType)
		{
			return Alert(htmlHelper, innerHtml, null, alertType);
		}

		public static MvcHtmlString Alert(this HtmlHelper htmlHelper, MvcHtmlString innerHtml, string headingText, AlertType alertType)
		{
			return Alert(htmlHelper, (innerHtml == null) ? null : innerHtml.ToHtmlString(), headingText, alertType);
		}

		public static MvcHtmlString Alert(this HtmlHelper htmlHelper, string innerHtml, string headingText, AlertType alertType)
		{
			if (htmlHelper.ViewData.ModelState.IsValid
			    || string.IsNullOrEmpty(innerHtml))
			{
				return MvcHtmlString.Empty;
			}

			var container = new TagBuilder("div");
			container.AddCssClass("alert");

			var alertTypeClassName = alertType.ToDescription();

			if (!string.IsNullOrEmpty(alertTypeClassName))
			{
				container.AddCssClass(alertTypeClassName);
			}

			if (!string.IsNullOrWhiteSpace(headingText))
			{
				container.AddCssClass("alert-block");

				var heading = new TagBuilder("h4");
				heading.AddCssClass("alert-heading");
				heading.SetInnerText(headingText);

				innerHtml = string.Concat(heading, innerHtml);
			}

			var closeLink = new TagBuilder("a");
			closeLink.AddCssClass("close js");
			closeLink.Attributes["data-dismiss"] = "alert";
			closeLink.Attributes["href"] = "#";
			closeLink.SetInnerText("×");

			innerHtml = string.Concat(closeLink, innerHtml);

			container.InnerHtml = innerHtml;

			return MvcHtmlString.Create(container.ToString());
		}
	}
}